<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI对话系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .message-fade-in {
            animation: fadeIn 0.3s ease-in-out;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .typing-indicator {
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: #9ca3af;
            margin: 0 2px;
            animation: typing 1.4s infinite ease-in-out;
        }
        
        .typing-indicator:nth-child(1) { animation-delay: -0.32s; }
        .typing-indicator:nth-child(2) { animation-delay: -0.16s; }
        
        @keyframes typing {
            0%, 80%, 100% { transform: scale(0.8); opacity: 0.5; }
            40% { transform: scale(1); opacity: 1; }
        }
        
        .chat-container {
            scrollbar-width: thin;
            scrollbar-color: #cbd5e0 #f7fafc;
        }
        
        .chat-container::-webkit-scrollbar {
            width: 6px;
        }
        
        .chat-container::-webkit-scrollbar-track {
            background: #f7fafc;
            border-radius: 3px;
        }
        
        .chat-container::-webkit-scrollbar-thumb {
            background: #cbd5e0;
            border-radius: 3px;
        }
        
        .chat-container::-webkit-scrollbar-thumb:hover {
            background: #a0aec0;
        }
        
        .sidebar {
            transition: all 0.3s ease;
        }
        
        @media (max-width: 768px) {
            .sidebar {
                position: fixed;
                left: -100%;
                z-index: 40;
                height: 100vh;
                width: 80%;
            }
            
            .sidebar.open {
                left: 0;
            }
            
            .overlay {
                display: none;
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background-color: rgba(0, 0, 0, 0.5);
                z-index: 30;
            }
            
            .overlay.open {
                display: block;
            }
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen flex">
    <!-- 移动端遮罩层 -->
    <div id="overlay" class="overlay"></div>
    
    <!-- 侧边栏 -->
    <div id="sidebar" class="sidebar bg-white w-64 flex flex-col border-r border-gray-200">
        <!-- 新建聊天按钮 -->
        <div class="p-4 border-b border-gray-200">
            <button id="newChatBtn" class="w-full bg-indigo-600 text-white px-4 py-2 rounded-lg hover:bg-indigo-700 transition-colors duration-200 flex items-center justify-center">
                <i class="fas fa-plus mr-2"></i>
                <span>新建聊天</span>
            </button>
        </div>
        
        <!-- 聊天列表 -->
        <div id="chatList" class="flex-1 overflow-y-auto p-2">
            <!-- 聊天项将通过JS动态添加 -->
        </div>
        
        <!-- 用户信息区域 -->
        <div class="p-4 border-t border-gray-200">
            <div class="flex items-center">
                <div class="h-10 w-10 rounded-full bg-indigo-500 flex items-center justify-center text-white">
                    <i class="fas fa-user"></i>
                </div>
                <div class="ml-3">
                    <p class="text-sm font-medium text-gray-900">用户</p>
                    <p class="text-xs text-gray-500">在线</p>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 主内容区域 -->
    <div class="flex-1 flex flex-col">
        <!-- 顶部栏 -->
        <header class="bg-white border-b border-gray-200 p-4 flex items-center justify-between">
            <div class="flex items-center">
                <button id="menuToggle" class="md:hidden text-gray-500 hover:text-gray-700 mr-4">
                    <i class="fas fa-bars text-xl"></i>
                </button>
                <h1 id="currentChatTitle" class="text-xl font-semibold text-gray-800">新对话</h1>
            </div>
            <div class="flex items-center space-x-4">
                <div id="statusIndicator" class="text-sm text-gray-500 hidden">
                    <i class="fas fa-circle text-green-500 mr-1 animate-pulse"></i>
                    <span>AI正在思考中...</span>
                </div>
                <button id="renameChatBtn" class="text-gray-500 hover:text-indigo-600">
                    <i class="fas fa-edit"></i>
                </button>
            </div>
        </header>
        
        <!-- 对话区域 -->
        <div id="chatContainer" class="flex-1 bg-white p-4 overflow-y-auto chat-container">
            <div class="text-center text-gray-500 py-8" id="emptyState">
                <i class="fas fa-robot text-4xl mb-4 text-indigo-400"></i>
                <p class="text-lg font-medium">欢迎使用AI助手</p>
                <p class="mt-2">开始一个新的对话，或者从左侧选择已有的对话</p>
            </div>
            <!-- 对话消息将在这里动态添加 -->
        </div>
        
        <!-- 输入区域 -->
        <div class="bg-white border-t border-gray-200 p-4">
            <div class="max-w-4xl mx-auto">
                <div class="flex space-x-2">
                    <input 
                        type="text" 
                        id="messageInput" 
                        placeholder="输入您的问题..." 
                        class="flex-1 border border-gray-300 rounded-lg px-4 py-3 focus:outline-none focus:ring-2 focus:ring-indigo-500"
                        maxlength="500"
                    >
                    <button 
                        id="sendButton" 
                        class="bg-indigo-600 text-white px-6 py-3 rounded-lg hover:bg-indigo-700 transition-colors duration-200 flex items-center disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                        <span>发送</span>
                        <i class="fas fa-paper-plane ml-2"></i>
                    </button>
                </div>
                <div class="flex justify-between items-center mt-2">
                    <span id="charCount" class="text-xs text-gray-500">0/500</span>
                    <div class="text-xs text-gray-500">
                        <span>按 Enter 发送</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 重命名模态框 -->
    <div id="renameModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-lg p-6 w-96">
            <h3 class="text-lg font-medium text-gray-900 mb-4">重命名对话</h3>
            <input 
                type="text" 
                id="renameInput" 
                class="w-full border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500"
                placeholder="输入新名称"
            >
            <div class="mt-4 flex justify-end space-x-2">
                <button id="cancelRename" class="px-4 py-2 text-gray-600 hover:text-gray-800">取消</button>
                <button id="confirmRename" class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700">确认</button>
            </div>
        </div>
    </div>

    <script>
        // 获取DOM元素
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('overlay');
        const menuToggle = document.getElementById('menuToggle');
        const newChatBtn = document.getElementById('newChatBtn');
        const chatList = document.getElementById('chatList');
        const chatContainer = document.getElementById('chatContainer');
        const messageInput = document.getElementById('messageInput');
        const sendButton = document.getElementById('sendButton');
        const emptyState = document.getElementById('emptyState');
        const charCount = document.getElementById('charCount');
        const statusIndicator = document.getElementById('statusIndicator');
        const currentChatTitle = document.getElementById('currentChatTitle');
        const renameChatBtn = document.getElementById('renameChatBtn');
        const renameModal = document.getElementById('renameModal');
        const renameInput = document.getElementById('renameInput');
        const cancelRename = document.getElementById('cancelRename');
        const confirmRename = document.getElementById('confirmRename');
        
        // 当前活动的事件源
        let currentEventSource = null;
        // 当前选中的聊天ID
        let currentChatId = null;
        // 聊天数据存储
        let chats = {};
        
        // 初始化
        function init() {
            // 从本地存储加载聊天数据
            loadChatsFromStorage();
            
            // 如果没有聊天，创建一个默认聊天
            if (Object.keys(chats).length === 0) {
                createNewChat();
            } else {
                // 显示第一个聊天
                const firstChatId = Object.keys(chats)[0];
                switchToChat(firstChatId);
            }
            
            // 绑定事件
            bindEvents();
        }
        
        // 绑定事件
        function bindEvents() {
            // 字符计数更新
            messageInput.addEventListener('input', () => {
                charCount.textContent = `${messageInput.value.length}/500`;
            });
            
            // 发送消息
            sendButton.addEventListener('click', sendMessage);
            
            // 回车键发送
            messageInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter' && !sendButton.disabled) {
                    sendMessage();
                }
            });
            
            // 新建聊天
            newChatBtn.addEventListener('click', createNewChat);
            
            // 菜单切换（移动端）
            menuToggle.addEventListener('click', () => {
                sidebar.classList.add('open');
                overlay.classList.add('open');
            });
            
            // 遮罩层点击关闭侧边栏
            overlay.addEventListener('click', () => {
                sidebar.classList.remove('open');
                overlay.classList.remove('open');
            });
            
            // 重命名相关事件
            renameChatBtn.addEventListener('click', openRenameModal);
            cancelRename.addEventListener('click', closeRenameModal);
            confirmRename.addEventListener('click', confirmRenameAction);
            
            // 页面卸载时关闭EventSource
            window.addEventListener('beforeunload', () => {
                if (currentEventSource) {
                    currentEventSource.close();
                }
            });
        }
        
        // 从本地存储加载聊天数据
        function loadChatsFromStorage() {
            const savedChats = localStorage.getItem('aiChats');
            if (savedChats) {
                chats = JSON.parse(savedChats);
                renderChatList();
            }
        }
        
        // 保存聊天数据到本地存储
        function saveChatsToStorage() {
            localStorage.setItem('aiChats', JSON.stringify(chats));
        }
        
        // 创建新聊天
        function createNewChat() {
            const chatId = 'chat_' + Date.now();
            const chatTitle = '新对话';
            
            chats[chatId] = {
                id: chatId,
                title: chatTitle,
                messages: []
            };
            
            saveChatsToStorage();
            renderChatList();
            switchToChat(chatId);
            
            // 移动端关闭侧边栏
            sidebar.classList.remove('open');
            overlay.classList.remove('open');
        }
        
        // 切换到指定聊天
        function switchToChat(chatId) {
            currentChatId = chatId;
            currentChatTitle.textContent = chats[chatId].title;
            renderChatMessages();
            
            // 更新聊天列表中的活动状态
            document.querySelectorAll('.chat-item').forEach(item => {
                if (item.dataset.chatId === chatId) {
                    item.classList.add('bg-indigo-50', 'border-indigo-500');
                } else {
                    item.classList.remove('bg-indigo-50', 'border-indigo-500');
                }
            });
        }
        
        // 删除聊天
        function deleteChat(chatId) {
            if (Object.keys(chats).length <= 1) {
                alert('至少需要保留一个对话');
                return;
            }
            
            if (confirm('确定要删除这个对话吗？')) {
                delete chats[chatId];
                saveChatsToStorage();
                renderChatList();
                
                // 如果删除的是当前聊天，切换到另一个聊天
                if (currentChatId === chatId) {
                    const remainingChatIds = Object.keys(chats);
                    if (remainingChatIds.length > 0) {
                        switchToChat(remainingChatIds[0]);
                    } else {
                        createNewChat();
                    }
                }
            }
        }
        
        // 打开重命名模态框
        function openRenameModal() {
            if (!currentChatId) return;
            
            renameInput.value = chats[currentChatId].title;
            renameModal.classList.remove('hidden');
        }
        
        // 关闭重命名模态框
        function closeRenameModal() {
            renameModal.classList.add('hidden');
        }
        
        // 确认重命名
        function confirmRenameAction() {
            if (!currentChatId) return;
            
            const newTitle = renameInput.value.trim();
            if (newTitle) {
                chats[currentChatId].title = newTitle;
                currentChatTitle.textContent = newTitle;
                saveChatsToStorage();
                renderChatList();
            }
            
            closeRenameModal();
        }
        
        // 渲染聊天列表
        function renderChatList() {
            chatList.innerHTML = '';
            
            Object.values(chats).forEach(chat => {
                const chatItem = document.createElement('div');
                chatItem.className = `chat-item p-3 rounded-lg border border-transparent mb-2 cursor-pointer hover:bg-gray-100 ${currentChatId === chat.id ? 'bg-indigo-50 border-indigo-500' : ''}`;
                chatItem.dataset.chatId = chat.id;
                
                chatItem.innerHTML = `
                    <div class="flex justify-between items-center">
                        <div class="flex items-center truncate">
                            <i class="fas fa-comment text-gray-500 mr-2"></i>
                            <span class="truncate">${chat.title}</span>
                        </div>
                        <div class="flex space-x-1 opacity-0 group-hover:opacity-100 transition-opacity">
                            <button class="text-gray-400 hover:text-indigo-600 p-1 edit-chat" title="重命名">
                                <i class="fas fa-edit text-xs"></i>
                            </button>
                            <button class="text-gray-400 hover:text-red-600 p-1 delete-chat" title="删除">
                                <i class="fas fa-trash text-xs"></i>
                            </button>
                        </div>
                    </div>
                `;
                
                // 点击聊天项切换聊天
                chatItem.addEventListener('click', (e) => {
                    if (!e.target.closest('.edit-chat') && !e.target.closest('.delete-chat')) {
                        switchToChat(chat.id);
                        
                        // 移动端关闭侧边栏
                        sidebar.classList.remove('open');
                        overlay.classList.remove('open');
                    }
                });
                
                // 重命名按钮
                const editBtn = chatItem.querySelector('.edit-chat');
                editBtn.addEventListener('click', (e) => {
                    e.stopPropagation();
                    switchToChat(chat.id);
                    openRenameModal();
                });
                
                // 删除按钮
                const deleteBtn = chatItem.querySelector('.delete-chat');
                deleteBtn.addEventListener('click', (e) => {
                    e.stopPropagation();
                    deleteChat(chat.id);
                });
                
                chatList.appendChild(chatItem);
            });
        }
        
        // 渲染聊天消息
        function renderChatMessages() {
            chatContainer.innerHTML = '';
            
            if (!currentChatId || chats[currentChatId].messages.length === 0) {
                emptyState.style.display = 'block';
                return;
            }
            
            emptyState.style.display = 'none';
            
            chats[currentChatId].messages.forEach(message => {
                addMessageToContainer(message.content, message.role, false);
            });
            
            // 滚动到底部
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }
        
        // 发送消息函数
        function sendMessage() {
            const message = messageInput.value.trim();
            if (!message || !currentChatId) return;

            // 禁用发送按钮
            sendButton.disabled = true;
            
            // 清空输入框
            messageInput.value = '';
            charCount.textContent = '0/500';

            // 隐藏空状态
            if (emptyState) {
                emptyState.style.display = 'none';
            }

            // 添加用户消息
            addMessageToContainer(message, 'user');
            
            // 保存用户消息到聊天记录
            chats[currentChatId].messages.push({
                role: 'user',
                content: message
            });
            
            // 更新聊天标题（如果是第一条消息）
            if (chats[currentChatId].messages.length === 1) {
                const newTitle = message.length > 20 ? message.substring(0, 20) + '...' : message;
                chats[currentChatId].title = newTitle;
                currentChatTitle.textContent = newTitle;
                saveChatsToStorage();
                renderChatList();
            }

            // 显示AI正在思考状态
            statusIndicator.classList.remove('hidden');
            
            // 添加AI消息容器
            const aiMessageElement = addMessageToContainer('', 'assistant', true);
            
            // 调用API
            callChatAPI(message, aiMessageElement);
        }

        // 添加消息到对话容器
        function addMessageToContainer(content, sender, isTyping = false) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `flex ${sender === 'user' ? 'justify-end' : 'justify-start'} mb-4 message-fade-in`;
            
            // 添加头像
            const avatarDiv = document.createElement('div');
            avatarDiv.className = `flex-shrink-0 h-8 w-8 rounded-full flex items-center justify-center ${sender === 'user' ? 'bg-indigo-500 ml-2' : 'bg-gray-300 mr-2'}`;
            
            if (sender === 'user') {
                avatarDiv.innerHTML = '<i class="fas fa-user text-white text-sm"></i>';
            } else {
                avatarDiv.innerHTML = '<i class="fas fa-robot text-gray-700 text-sm"></i>';
            }
            
            const bubbleDiv = document.createElement('div');
            bubbleDiv.className = `max-w-[80%] p-3 rounded-lg ${
                sender === 'user' 
                    ? 'bg-indigo-500 text-white rounded-br-none' 
                    : 'bg-gray-200 text-gray-800 rounded-bl-none'
            }`;
            
            if (isTyping) {
                bubbleDiv.id = 'typingMessage';
                const typingDiv = document.createElement('div');
                typingDiv.className = 'flex space-x-1 items-center';
                typingDiv.innerHTML = `
                    <span class="typing-indicator"></span>
                    <span class="typing-indicator"></span>
                    <span class="typing-indicator"></span>
                `;
                bubbleDiv.appendChild(typingDiv);
            } else {
                // 处理换行，将换行符转换为<br>标签
                const formattedContent = content.replace(/\n/g, '<br>');
                bubbleDiv.innerHTML = formattedContent;
            }
            
            if (sender === 'user') {
                messageDiv.appendChild(bubbleDiv);
                messageDiv.appendChild(avatarDiv);
            } else {
                messageDiv.appendChild(avatarDiv);
                messageDiv.appendChild(bubbleDiv);
            }
            
            chatContainer.appendChild(messageDiv);
            
            // 滚动到底部
            chatContainer.scrollTop = chatContainer.scrollHeight;
            
            return bubbleDiv;
        }

        // 调用聊天API
        function callChatAPI(message, messageElement) {
            // 构建API URL - 这里假设后端接口已经处理了CORS
            const apiUrl = `http://localhost:8080/api/ollama/generate_stream_rag?ragTag=${encodeURIComponent('人员信息')}&message=${encodeURIComponent(message)}`;
            
            // 创建EventSource
            const eventSource = new EventSource(apiUrl);
            currentEventSource = eventSource;
            let responseText = '';
            
            eventSource.onmessage = function(event) {
                try {
                    // 解析服务器返回的JSON数据
                    const data = JSON.parse(event.data);
                    
                    // 检查是否有文本内容
                    if (data.result && data.result.output && data.result.output.text !== undefined) {
                        responseText += data.result.output.text;
                        
                        // 更新消息显示
                        messageElement.innerHTML = responseText;
                        
                        // 滚动到底部
                        chatContainer.scrollTop = chatContainer.scrollHeight;
                    }
                    
                    // 检查是否结束
                    if (data.result && data.result.metadata && data.result.metadata.finishReason === 'stop') {
                        completeResponse(eventSource, messageElement, responseText);
                    }
                } catch (error) {
                    console.error('解析响应数据出错:', error);
                    // 如果解析出错，显示错误信息
                    messageElement.innerHTML = '<span class="text-red-500">抱歉，解析响应时出错。</span>';
                    completeResponse(eventSource, messageElement, '抱歉，解析响应时出错。');
                }
            };
            
            eventSource.onerror = function(event) {
                console.error('EventSource错误:', event);
                messageElement.innerHTML = '<span class="text-red-500">抱歉，连接服务器时发生错误，请检查网络连接或稍后再试。</span>';
                completeResponse(eventSource, messageElement, '抱歉，连接服务器时发生错误，请检查网络连接或稍后再试。');
            };
            
            // 添加取消按钮
            const cancelButton = document.createElement('button');
            cancelButton.className = 'mt-2 text-xs text-red-500 hover:text-red-700 flex items-center';
            cancelButton.innerHTML = '<i class="fas fa-times mr-1"></i>取消请求';
            cancelButton.onclick = function() {
                eventSource.close();
                messageElement.innerHTML += '<br><span class="text-gray-500 text-xs">[已取消]</span>';
                completeResponse(eventSource, messageElement, responseText + '\n\n[已取消]');
                cancelButton.remove();
            };
            
            messageElement.appendChild(cancelButton);
        }

        // 完成响应处理
        function completeResponse(eventSource, messageElement, responseText) {
            if (eventSource) {
                eventSource.close();
            }
            currentEventSource = null;
            statusIndicator.classList.add('hidden');
            sendButton.disabled = false;
            
            // 移除取消按钮
            const cancelButton = messageElement.querySelector('button');
            if (cancelButton) {
                cancelButton.remove();
            }
            
            // 保存AI回复到聊天记录
            if (currentChatId && responseText) {
                chats[currentChatId].messages.push({
                    role: 'assistant',
                    content: responseText
                });
                saveChatsToStorage();
            }
        }

        // 初始化应用
        init();
    </script>
</body>
</html>